package com.controllers;

import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.authentication.encoding.PasswordEncoder;

import com.daos.EmployeeDao;
import com.model.Employee;

@Named
@ManagedBean
public class EmployeeController {

	private EmployeeDao employeeDao;

	public EmployeeController() {
	}

	@Inject
	public EmployeeController(EmployeeDao employeeDao) {
		this.employeeDao = employeeDao;
	}

	public List<Employee> getEmployees() {
		return employeeDao.getEmployees();
	}

	public void save(Employee employee) {

		processAndValidateUser(employee);

		employeeDao.save(employee);
	}

	private void processAndValidateUser(Employee employee) {
		if (employee.getPassword().isEmpty()) {
			String oldPassword = employeeDao.getPasswordForEmployee(employee
					.getId());
			employee.setPassword(oldPassword);
		}

		else {
			employee.setPassword(encondePassword(employee));
		}

		if (employee.getImage().isEmpty()) {
			String oldImage = employeeDao.getImageForEmployee(employee.getId());
			employee.setImage(oldImage);
		}

	}

	private String encondePassword(Employee employee) {
		PasswordEncoder encoder = new Md5PasswordEncoder();
		String hashedPass = encoder
				.encodePassword(employee.getPassword(), null);
		return hashedPass;
	}

	public Employee getLoggedInUser(String username) {
		return getEmployeeByUsername(username);

	}
	
	public String getCurrentUsername() {
		FacesContext currentInstance = FacesContext.getCurrentInstance();
		return currentInstance
				.getExternalContext().getRemoteUser();
	}


	public void delete(Employee selectedEmployee) {
		employeeDao.remove(selectedEmployee);
	}

	public Employee getEmployeeById(int id) {
		return employeeDao.getEmployeeById(id);
	}

	public Employee getEmployeeByUsername(String username) {
		return employeeDao.getEmployeeByUsername(username);
	}

}
